import { Component } from '@angular/core';
import { ApesField } from './apes-field';
import { ApiService } from '@core/services/http/api.service';
import { Events } from '@core/services/events/Events';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { SubjectService } from '@core/services/events/subject.service';
import { dateFormat } from '../../../../utils/utils';
import { addDays, endOfDay, startOfDay } from 'date-fns';

@Component({
  selector: 'formly-field-date-range',
  template: `
    <apes-range-picker [apesStyle]="{'width': '100%'}"
                       style="width: 100%;"
                       [apesFormat]="formatType"
                       [apesShowTime]="showTime"
                       [disabled]="to.disabled"
                       [formControl]="formControl"
                       [formlyAttributes]="field"
                       [apesRanges]="dateRange"
                       (ngModelChange)="onChange($event)"></apes-range-picker>
  `,
  host: {},
})
export class FormlyFieldDateRange extends ApesField {
  // yyyy-MM-dd  yyyy-MM-dd HH:mm:ss  yyyy-MM-dd HH:mm:ss SSS
  value = null;
  formatType: string = 'yyyy-MM-dd';
  showTime = false;

  dateRange = {
    '当天': [startOfDay(new Date()), endOfDay(new Date())],
    '近7天': [addDays(new Date(), -6), endOfDay(new Date())],
    '近30天': [addDays(new Date(), -29), endOfDay(new Date())],
    '近90天': [addDays(new Date(), -89), endOfDay(new Date())],
  };

  constructor(protected apiService: ApiService, protected events: Events, protected expressionService: ExpressionService, protected subject: SubjectService) {
    super(apiService, events, expressionService, subject);
  }

  get type() {
    return this.to.type || 'dateRange';
  }

  onChange(date: Date): void {
    if (!date || typeof date[0] != 'object') {
      return;
    }
    this.value = this.dataModel(date);
    this.formControl.patchValue(this.value);
  }

  ngOnInit() {
    this.addDefalutPlaceholder('请选择');
    if (this.to['valueFormatter']) {
      this.formatType = this.to['valueFormatter'];
      this.showTime = true;
    }
    if (this.formControl.value) {
      this.value = this.dataModel(this.formControl.value);
    }
  }

  dataModel(date) {
    let dateItem = [];
    if (date) {
      let dataModelStar = this.dateRangeFormat(this.formatType, new Date(date[0]), 'GTE');
      let dataModelEnd = this.dateRangeFormat(this.formatType, new Date(date[1]), 'LTE');
      dateItem.push(dataModelStar);
      dateItem.push(dataModelEnd);
    }
    return dateItem;
  }

  dateRangeFormat(type, value, operator) {
    let date;
    if (type != 'yyyy-MM-dd') {
      date = dateFormat(type, value);
    } else {
      let ope = operator == 'GTE' ? ' 00:00:00' : ' 23:59:59';
      date = dateFormat(type, value) + ope;
    }
    return date;
  }


}
